C++- CPP教程

C++ 多线程库 <thread>

C++11 引入了多线程支持,通过 <thread> 库,开发者可以轻松地在程序中实现并行处理。

本文将将介绍 <thread> 库的基本概念、定义、语法以及如何使用它来创建和管理线程。

线程是程序执行的最小单元,是操作系统能够进行运算调度的最小单位。

在多线程程序中,多个线程可以并行执行,提高程序的执行效率。

C++ <thread> 库概述

<thread> 库是 C++ 标准库的一部分,提供了创建和管理线程的基本功能,它包括以下几个关键组件:

  • std::thread :表示一个线程,可以创建、启动、等待和销毁线程。
  • std::this_thread :提供了一些静态成员函数,用于操作当前线程。
  • std::thread::id :线程的唯一标识符。

创建线程

要创建一个线程,你需要实例化 std::thread 类,并传递一个可调用对象(函数、lambda 表达式或对象的成员函数)作为参数。

示例代码
#include <iostream>#include <thread>voidprint_id(intid){std::cout<<"ID: "<<id<<", Thread ID: "<<std::this_thread::get_id()<<std::endl;}intmain(){std::threadt1(print_id,1);std::threadt2(print_id,2);}

启动线程

创建 std::thread 对象后,线程会立即开始执行,你可以调用 join() 方法来等待线程完成。

t1.join();

t2.join();

等待线程完成

join() 方法会阻塞当前线程,直到被调用的线程完成执行。

销毁线程

当线程执行完毕后,你可以使用 detach() 方法来分离线程,或者让 std::thread 对象超出作用域自动销毁。

t1.detach(); // 线程将继续运行,但无法再被 join 或 detach

实例:使用 <thread> 创建并行计算

下面是一个使用 <thread> 库实现的并行计算实例,计算两个数的和。

示例代码
#include <iostream>#include <thread>intsum=0;voidadd(inta,intb){sum+=a+b;}intmain(){inta=5;intb=10;std::threadt1(add, a, b);std::threadt2(add, a, b);t1.join();t2.join();std::cout<<"Sum: "<<sum<<std::endl;// 输出结果:Sum: 30}

输出结果为:

Sum: 30

以下实例我们将创建两个线程,每个线程都会执行一个简单的函数,该函数打印一个消息并休眠一段时间:

示例代码
#include <iostream>#include <thread>#include <chrono>// 简单的函数,在线程中执行voidprint_message(conststd::string&message,intdelay){std::this_thread::sleep_for(std::chrono::milliseconds(delay));std::cout<<message<<std::endl;}intmain(){// 创建两个线程,执行 print_message 函数std::threadt1(print_message,"Hello from thread 1",1000);std::threadt2(print_message,"Hello from thread 2",500);// 等待线程 t1 完成if(t1.joinable()){t1.join();}// 等待线程 t2 完成if(t2.joinable()){t2.join();}std::cout<<"Main thread finished."<<std::endl;return0;}

输出结果为:

Hello from thread 2

Hello from thread 1

Main thread finished.

注意事项

  • 线程安全:在多线程环境中,共享资源需要同步访问,以避免数据竞争。
  • 线程生命周期:确保在线程执行完毕后正确地处理线程对象,避免资源泄露。

类和函数

<thread> 库包含了一系列的类和函数,用于创建、管理和同步线程。

以下是对 C++ <thread> 库的详细介绍:

主要组件

  • std::thread
  • std::mutex
  • std::lock_guard
  • std::unique_lock
  • std::condition_variable
  • std::future 和 std::promise
  • std::async

std::thread

std::thread 类用于创建和管理线程。

示例代码
#include <iostream>#include <thread>voidprint_hello(){std::cout<<"Hello from thread!"<<std::endl;}intmain(){std::threadt(print_hello);t.join();// 等待线程 t 结束return0;}

重要方法

  • join() : 等待线程结束。
  • detach() : 将线程置于后台运行,不再等待线程结束。
  • joinable() : 检查线程是否可被 join 或 detach。

std::mutex

std::mutex 类用于同步对共享资源的访问。

示例代码
#include <iostream>#include <thread>#include <mutex>std::mutexmtx;// 创建一个全局 mutex 对象intshared_resource=0;// 共享资源// 线程函数voidincrement(){std::lock_guard<std::mutex>lock(mtx);// 上锁,保证线程安全++shared_resource;std::cout<<"Incremented shared_resource to "<<shared_resource<<std::endl;// lock 在 lock_guard 离开作用域时自动释放}intmain(){std::threadt1(increment);std::threadt2(increment);t1.join();// 等待线程 t1 完成t2.join();// 等待线程 t2 完成std::cout<<"Final value of shared_resource: "<<shared_resource<<std::endl;return0;}

std::lock_guard

std::lock_guard 是一个 RAII 风格的锁管理器,用于自动管理锁的生命周期。

示例代码
#include <iostream>#include <thread>#include <mutex>std::mutexmtx;voidprint_thread_id(intid){std::lock_guard<std::mutex>lock(mtx);std::cout<<"Thread ID: "<<id<<std::endl;}intmain(){std::threadt1(print_thread_id,1);std::threadt2(print_thread_id,2);t1.join();t2.join();return0;}

std::unique_lock

std::unique_lock 提供了比 std::lock_guard 更灵活的锁管理。

示例代码
#include <iostream>#include <thread>#include <mutex>std::mutexmtx;voidprint_thread_id(intid){std::unique_lock<std::mutex>lock(mtx);std::cout<<"Thread ID: "<<id<<std::endl;lock.unlock();// 可以手动解锁// ... 其他操作}intmain(){std::threadt1(print_thread_id,1);std::threadt2(print_thread_id,2);t1.join();t2.join();return0;}

std::condition_variable

std::condition_variable 用于线程间的等待和通知。

示例代码
#include <iostream>#include <thread>#include <mutex>#include <condition_variable>std::mutexmtx;std::condition_variablecv;boolready=false;voidprint_id(intid){std::unique_lock<std::mutex>lock(mtx);cv.wait(lock,[]{returnready;});std::cout<<"Thread ID: "<<id<<std::endl;}voidset_ready(){std::unique_lock<std::mutex>lock(mtx);ready=true;cv.notify_all();}intmain(){std::threadt1(print_id,1);std::threadt2(print_id,2);std::this_thread::sleep_for(std::chrono::seconds(1));set_ready();t1.join();t2.join();return0;}

std::future 和 std::promise

std::future 和 std::promise 用于线程间的结果传递。

示例代码
#include <iostream>#include <thread>#include <future>voidcalculate_square(std::promise<int>&&p,intx){p.set_value(x*x);}intmain(){std::promise<int>p;std::future<int>f=p.get_future();std::threadt(calculate_square, std::move(p),5);std::cout<<"Square: "<<f.get()<<std::endl;t.join();return0;}

std::async

std::async 用于启动异步任务,并返回一个 std::future。

示例代码
#include <iostream>#include <future>intcalculate_square(intx){returnx*x;}intmain(){std::future<int>result=std::async(calculate_square,5);std::cout<<"Square: "<<result.get()<<std::endl;return0;}

C++ 的 <thread> 库为开发者提供了强大的多线程支持。通过本文的介绍,我们应该能够理解线程的基本概念,并学会如何使用 <thread> 库来创建和管理线程。在实际开发中,合理利用多线程可以显著提高程序的性能和响应速度。